class Solution {
public:
    int mySqrt(int x)
    {
        long long lhs = 0, rhs = x;
        long long mid = lhs + (rhs - lhs + 1) / 2, num = mid * mid;

        while (lhs < rhs)
        {
            if (num <= x) lhs = mid;
            else rhs = mid - 1;

            mid = lhs + (rhs - lhs + 1) / 2;
            num = mid * mid;
        }

        return lhs;
    }
};